# !/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2022/4/12 11:03 PM
# @Author : 曹庭
# @File : orders.py
# @Software: PyCharm

from . import api
from course.utils.commons import login_required
from flask import g, current_app, jsonify, request
from course.utils.response_code import RET
from course.models import Course, Order, User
from course import db, constants
from course.utils.image_storage import storage


@api.route("/orders", methods=["POST"])
@login_required
def save_order():
    """
    保存订单
    :return:
    """
    user_id = g.user_id

    # 获取参数
    order_data = request.get_json()
    if not order_data:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    course_id = order_data.get("course_id")
    order_price = order_data.get("order_price")

    # 校验参数
    if not all([user_id, course_id, order_price]):
        return jsonify(errno=RET.PARAMERR, errmag="参数不完整")

    order = Order(user_id=user_id, course_id=course_id, order_price=order_price)

    try:
        db.session.add(order)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库异常")

    # 返回结果
    return jsonify(errno=RET.OK, errmsg="新增订单成功")


@api.route("/orders/cancel", methods=["POST"])
@login_required
def cancel_order():
    """
    取消订单
    :return:
    """
    user_id = g.user_id

    # 获取参数
    order_data = request.get_json()
    if not order_data:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    order_id = order_data.get("order_id")
    course_id = order_data.get("course_id")

    # 校验参数
    if not all([user_id, order_id, course_id]):
        return jsonify(errno=RET.PARAMERR, errmag="参数不完整")

    Order.query.filter_by(user_id=user_id, id=order_id, course_id=course_id).update({"order_status": "CANCELED"})

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库异常")

    # 返回结果
    return jsonify(errno=RET.OK, errmsg="订单已取消")


@api.route("/orders/delete", methods=["POST"])
@login_required
def delete_order():
    """
    删除订单
    :return:
    """
    user_id = g.user_id

    # 获取参数
    order_data = request.get_json()
    if not order_data:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    order_id = order_data.get("order_id")
    course_id = order_data.get("course_id")

    # 校验参数
    if not all([user_id, course_id, order_id]):
        return jsonify(errno=RET.PARAMERR, errmag="参数不完整")

    order = Order.query.filter_by(user_id=user_id, id=order_id, course_id=course_id).first()

    if order.order_status in ["WAIT_PAYMENT", "PAID", "COMPLETE"]:
        return jsonify(errno=RET.REQERR, errmsg="非已取消订单无法删除")

    try:
        db.session.delete(order)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库异常")

    # 返回结果
    return jsonify(errno=RET.OK, errmsg="订单已删除")


@api.route("/orders/info", methods=["POST"])
@login_required
def get_orderinfo():
    """
    获得订单详情
    :return:
    """
    user_id = g.user_id

    # 获取参数
    order_data = request.get_json()
    if not order_data:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    order_id = order_data.get("order_id")
    course_id = order_data.get("course_id")

    # 校验参数
    if not all([user_id, course_id, order_id]):
        return jsonify(errno=RET.PARAMERR, errmag="参数不完整")

    order = Order.query.filter_by(user_id=user_id, id=order_id, course_id=course_id).first()

    order_dict = order.to_dict()

    # 返回结果
    return jsonify(errno=RET.OK, errmsg="成功获取详情", data={
        "order_dict": order_dict
    })


@api.route("/orders/list", methods=["POST"])
@login_required
def get_order_list():
    """
    获得订单列表
    :return:
    """
    user_id = g.user_id

    try:
        orders = Order.query.filter_by(user_id=user_id).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="数据库查询失败")

    order_list = []

    for order in orders:
        order_dict = order.to_dict()
        try:
            # print(order_dict["course_id"])
            course = Course.query.filter_by(id=order_dict["course_id"]).first()
            course_dict = course.to_basic_dict()
            order_dict["title"] = course_dict["title"]
            order_dict["index_image_url"] = course_dict["index_image_url"]
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(code=RET.DBERR, msg="数据库查询失败")
        order_list.append(order_dict)
    print(order_list)
    # 返回结果
    return jsonify(code=RET.OK, msg="成功获取详情", data=order_list)


@api.route("/orders/listAll", methods=["POST"])
@login_required
def get_order_list_all():
    """
    获得订单列表
    :return:
    """
    user_id = g.user_id

    if user_id != 1:
        return jsonify(code=RET.RIGHTSERR, msg="此账号无权限")

    req_dict = request.get_json()
    curr = req_dict.get("curr")
    nums = req_dict.get("nums")
    print(curr)
    print(nums)
    searchParams = req_dict.get("searchParams")
    print(searchParams)

    order_id = searchParams["order_id"]
    trade_no = searchParams["trade_no"]
    user_name = searchParams["user_name"]
    course_id = searchParams["course_id"]

    filter_list = []

    order_list = []
    total = 0

    # 有搜索条件时进入
    if any([order_id, trade_no, course_id, user_name]):
        if order_id:
            print(order_id)
            filter_list.append(Order.id == order_id)
        if trade_no:
            print(trade_no)
            filter_list.append(Order.trade_no == trade_no)
        if user_name:
            print(user_name)
            try:
                user = User.query.filter_by(user_name=user_name).first()
                user_id = user.id
                filter_list.append(Order.user_id == user_id)
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(code=RET.DBERR, msg="数据库查询失败")
        if course_id:
            print(course_id)
            filter_list.append(Order.course_id == course_id)

        try:
            paginate = Order.query.filter(*filter_list).paginate(page=curr, per_page=nums)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(code=RET.DBERR, msg="数据库查询失败")

        orders = paginate.items
        # print(orders)
        total = paginate.total
        for order in orders:
            order_dict = order.to_dict()
            # print(order_dict)
            order_list.append(order_dict)
        print(order_list)
        # 返回结果
        return jsonify(code=RET.OK, count=total, msg="所有订单获取成功9999", data=order_list)

    # 查询全部订单
    try:
        paginate = Order.query.paginate(page=curr, per_page=nums)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="数据库查询失败")

    # course_list = []

    orders = paginate.items
    total = paginate.total
    for order in orders:
        order_dict = order.to_dict()
        print(order_dict)
        order_list.append(order_dict)
    print(order_list)

    # 返回结果
    return jsonify(code=RET.OK, count=total, msg="所有订单获取成功1234", data=order_list)